<template>
	<view class="search-pg">
		<u-navbar title="详情" :autoBack="true" :placeholder="true"></u-navbar>
		<view style="padding: 10px;">
			<u-skeleton rows="3" title :loading="loading"></u-skeleton>
		</view>
		<view title="用户信息" :border="false" class="u-m-t-20" v-show="!loading">
			<view class="detail-row" v-for="(item, index) in dataList" :key="index">
				<text class="label">{{ item.label }}：</text>
				<view class="value-wrap">
					<text class="value">{{ getDataVlaue(item.key,item) || '-' }}</text>
					<image class="copy-img" v-if="item.copyable &&  getDataVlaue(item.key)"
						src="@/static/images/copy.png" @click="copyText(item)"></image>
				</view>
			</view>
		</view>
		<view v-show="!loading">
			<view class="label" style="display: block;padding: 6px;">资产照片：</view>
			<view class="detail-row-img">
				<view v-for="file in files" class="item-img">
					<u-image style="width: 100%;height: 100%;" width="100%" height="100%" :src="file.url"
						@click="previewImage(file.url)"></u-image>
					<!-- <image :src="file.url" ></image> -->
				</view>
			</view>
		</view>
		
		<ble-print ref="blePrintRef"></ble-print>
	</view>
</template>

<script>
	import {
		getDetailByBarcodeNumber
	} from '@/api/asset/index.js'
	import dayjs from 'dayjs'
	import BlePrint from '@/components/ble-print/index.vue'
	import {
		getDictListAllSimple
	} from '@/api/dict/index.js'
	export default {
		data() {
			return {
				loading: true,
				imgUrl: '',
				dataObj: {},
				files: [],
				businessList:[],
				assetTypeList:[],
				unitOfMeasurementList:[],
				newnessRateList:[],
				barcodeNumber:'',
				dataList: [{
						label: '条码编号',
						key: 'barcodeNumber',
						copyable: true
					},
					{
						label: '资产分类',
						type: 'dict',
						key: 'assetType',
					},
					{
						label: '资产名称',
						key: 'title',
						copyable: true
					},
					{
						label: '资产编号',
						key: 'assetNumber',
						copyable: true
					},
					{
						label: '使用部门',
						value: '510123199001019876',
						key: 'useDeptName',
					},
					{
						label: '使用人',
						value: '510123199001019876',
						key: 'useUserName',
					},
					{
						label: '管理部门',
						key: 'managementDeptName',
					},
					{
						label: '管理人',
						key: 'managementUserName',
					},
					{
						label: '品牌',
						key: 'brand',
					},
					{
						label: '规格型号',
						value: '510123199001019876',
						key: 'specificationModel',
						copyable: true
					},
					{
						label: '数量',
						value: '510123199001019876',
						key: 'number',
					},
					{
						label: '资产原值',
						value: '510123199001019876',
						key: 'originalValue',
					},
					{
						label: '生产日期',
						key: 'obtainTime',
						type: 'date'
					},
					{
						label: '存放地点',
						key: 'storageLocation',
						copyable: true
					},
					{
						label: '业务状态',
						type: 'dict',
						key: 'businessStatus',
					},
					{
						label: '成新率',
						type: 'dict',
						key: 'newnessRate',
					},
					{
						label: '财务记账日期',
						key: 'financialAccountingTime',
						type: 'date'
					},
					{
						label: '创建时间',
						key: 'createTime',
						type: 'time'
					},
					{
						label: '备注',
						key: 'remark',
					}
				]
			}
		},
		components:{
			BlePrint
		},
		onLoad: function(options) {
			if (!options.id) {
				uni.showToast({
					icon:'error',
					title:"参数不合法"
				})
			}
			this.barcodeNumber = options.id
		},
		mounted() {
			this.getDictList()
			this.getDetail()
		},
		destroyed() {
			uni.hideLoading()
		},
		methods: {
			async getDictList() {
				const ret = await getDictListAllSimple()
				const dictData = ret.data || []
				// 业务状态
				const businessList = dictData.filter(v => v.dictType === 'business_status')
				this.businessList = businessList
				// 资产分类
				const assetTypeList = dictData.filter(v => v.dictType === 'asset_classification')
				this.assetTypeList = assetTypeList
				// 成新率
				const newnessRateList = dictData.filter(v => v.dictType === 'newness_rate')
				this.newnessRateList = newnessRateList
				// 计量单位
				const unitOfMeasurementList = dictData.filter(v => v.dictType === 'unit_of_measurement')
				this.unitOfMeasurementList = unitOfMeasurementList
			},
			formatDictValue(val,data=[]){
				const oneData = data.find(v=>v.value==val)
				if (oneData){
					return oneData.label
				}
				return val
			},
			async getDetail() {
				uni.showLoading({
					title:"数据加载中..."
				})
				this.loading = true
				const ret = await getDetailByBarcodeNumber(this.barcodeNumber)
				uni.hideLoading()
				this.loading = false
				const data = ret.data || {}
				this.dataObj = data
				const files = JSON.parse(data.files || '[]')
				this.files = files
			},
			saveImageToAlbum(imagePath) {
			    uni.saveImageToPhotosAlbum({
			        filePath: imagePath, // 图片文件路径
			        success: function () {
			            uni.showToast({ title: '保存成功' });
			        },
			        fail: function (err) {
			            uni.showToast({ title: '保存失败', icon: 'none' });
			            console.log('保存失败', err);
			        }
			    });
			},
			downloadAndSaveImage(url) {
				const _this =this;
			    uni.downloadFile({
			        url: url, // 图片地址
			        success: function (res) {
			            if (res.statusCode === 200) {
			                const tempFilePath = res.tempFilePath; // 临时路径
			                _this.saveImageToAlbum(tempFilePath); // 保存到相册
			            } else {
			                console.log('下载失败', res.errMsg);
			            }
			        },
			        fail: function (err) {
			            console.log('下载失败', err);
			        }
			    });
			},
			previewImage(imgUrl) {
				this.imgUrl = imgUrl
				const _this = this;
				const files =(this.files||[]).map(v=>v.url)
				uni.previewImage({
					current: this.imgUrl, // 当前预览的图片
					urls: files, // 如果是多张图，这里可以传整个图片数组
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							const url = files[data.index]
							_this.downloadAndSaveImage(url)
						},
						fail: function(err) {
							console.log(err.errMsg)
						}
					}
				})
			},
			getDataVlaue(key, item = {}) {
				let text = this.dataObj[key]
				if (text && item.type) {
					if (item.type === 'time') {
						text = dayjs(text).format("YYYY-MM-DD HH:mm:ss")
					} else if (item.type === 'date') {
						text = dayjs(text).format("YYYY-MM-DD")
					}else if(item.type='dict'){
						if(item.key=='assetType'){
							text = this.formatDictValue(text,this.assetTypeList)
						}else if(item.key=='businessStatus'){
							text = this.formatDictValue(text,this.businessList)
						}else if(item.key=='newnessRate'){
							text = this.formatDictValue(text,this.newnessRateList)
						}else if(item.key=='newnessRate'){
							text = this.formatDictValue(text,this.newnessRateList)
						}
					}
				}
				return text
			},
			copyText(item) {
				const text = this.getDataVlaue(item.key)
				uni.setClipboardData({
					data: text,
					success: () => {
						uni.showToast({
							title: '已复制',
							icon: 'success'
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/uni_modules/uview-ui/index.scss";

	.search-pg {
		background-color: #fff;
	}

	.detail-row {
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 8px 6px;
	}

	.copy-img {
		width: 16px;
		height: 16px;
		margin-left: 4px;
	}

	.label {
		width: 180rpx;
		color: #666;
		font-size: 28rpx;
	}

	.detail-row-img {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}

	.item-img {
		min-width: 30%;
		height: 80px;
		border-radius: 4px;
		border: 1px solid #eee;
		margin: 6px;
	}

	.value-wrap {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.value {
		font-size: 30rpx;
		color: #333;
	}
	::v-deep .u-navbar--fixed{
		box-shadow:0 1px 10px rgba(0, 0, 0, 0.1);
	}
</style>